package org.luxor.common.kettle.client.impl;

import org.luxor.common.kettle.client.IKettleClient;
import org.luxor.common.kettle.config.properties.KettleProperties;
import org.luxor.common.kettle.exception.KettleException;
import org.pentaho.di.job.Job;
import org.pentaho.di.job.JobMeta;
import org.pentaho.di.repository.Repository;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransMeta;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.util.Assert;

import java.io.InputStream;

/**
 * Kettle 脚本启动服务
 *
 * @author Mr.yan  @dateI2022/4/6
 */
public class KettleClientImpl implements IKettleClient {
    private static final Logger log = LoggerFactory.getLogger(KettleClientImpl.class);

    private final ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();

    private final KettleProperties properties;

    public KettleClientImpl(KettleProperties properties) {
        this.properties = properties;
    }

    @Override
    public void runKtr(String filename, String[] arguments) {
        Assert.notNull(filename, "这个filename参数是必填项,不允许为空");

        String fileScriptName = properties.getScriptLocationPrefix() + filename;
        log.info("开始 执行ktr文件. 脚本文件:{}", fileScriptName);
        try {
            InputStream xmlStream = resourceResolver.getResource(fileScriptName).getInputStream();
            TransMeta tm = new TransMeta(xmlStream, null, true, null, null);
            Trans trans = new Trans(tm);
            trans.setLogLevel(properties.getLogLevel());
            trans.execute(arguments);
            trans.waitUntilFinished();
            log.info("完成 ktr文件执行. 脚本文件:{}", fileScriptName);
        } catch (Exception e) {
            log.error("执行ktr文件({})失败", fileScriptName, e);
            throw new KettleException("执行ktr文件(" + fileScriptName + ")失败", e);
        }
    }


    @Override
    public void runKjb(String filename, Repository repository) {
        Assert.notNull(filename, "这个filename参数是必填项,不允许为空");

        String fileScriptName = properties.getScriptLocationPrefix() + filename;
        log.info("开始 执行kjb文件. 脚本文件:{}", fileScriptName);
        try {
            InputStream xmlStream = resourceResolver.getResource(fileScriptName).getInputStream();
            JobMeta jm = new JobMeta(xmlStream, null, null);
            Job job = new Job(repository, jm);
            job.setLogLevel(properties.getLogLevel());
            job.start();
            job.waitUntilFinished();
            log.info("完成 kjb文件执行. 脚本文件:{}", fileScriptName);
        } catch (Exception e) {
            log.error("执行kjb文件({})失败", fileScriptName, e);
            throw new KettleException("执行kjb文件(" + fileScriptName + ")失败", e);
        }
    }
}
